/*
 * @author Javier A. Ramírez M.
 * jaramirez85@yahoo.es
 */
package com.jav;

import com.jav.inter.Constantes;
import com.jav.per.PersisPedido;
import com.jav.per.PersisProducto;
import com.jav.per.Persistencia;
import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.animations.CommonTransitions;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.util.Resources;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import com.jav.per.PersisSetup;

public class ExportForm extends Form implements Constantes {

    private Button bt_exp;
    private Button bt_borrar;
    private Button bt_enviar_pedidos_web;
    //private Button bt_enviar_url;
    private static final VentanaEspera waiting = new VentanaEspera("EXPORTANDO...");
    private Image imgError;
    private Resources res = null;

    public ExportForm() {
        super("DATOS");
        setLayout(new BoxLayout(BoxLayout.Y_AXIS));
        try {
            setTransitionInAnimator(CommonTransitions.createFade(500));
            setTransitionOutAnimator(CommonTransitions.createFade(500));
        } catch (Exception e) {
        }


        res = Datos.getInstance().getRes();


        addCommand(new Command("Atrás", res.getImage("bck.png")) {

            public void actionPerformed(ActionEvent evt) {
                CapMovil.getMainForm().show();
            }
        });

        bt_exp = new Button("EXPORTAR");
        bt_exp.getStyle().setMargin(20, 3, 5, 5);
        bt_exp.setAlignment(CENTER);
        
        bt_enviar_pedidos_web = new Button("ENVIAR PEDIDOS");
        bt_enviar_pedidos_web.getStyle().setMargin(20, 3, 5, 5);
        bt_enviar_pedidos_web.setAlignment(CENTER);
        
        bt_enviar_pedidos_web.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                new Thread(new Runnable() {

                    public void run() {
                        waiting.showModeless();
                        try {
                            StringBuffer data = new StringBuffer();
                            data.append(leerRsPedidoWeb())
                            .append(leerRsDetalleWeb());
                            PersisSetup pd = Datos.getInstance().getPersisSetup();
                            System.out.println("Datos*****: "+ data.toString());
                            CapturaForm.enviarDatos(data, pd, "2");
                            
                        } catch (Exception e) {
                            e.printStackTrace();
                            Command okCommand = new Command("OK");
                            imgError = res.getImage("cancel.png");
                            Dialog.show("Falló!", "Error al enviar los pedidos:\n" + e.getMessage(),
                                    okCommand, new Command[]{okCommand}, Dialog.TYPE_ERROR, imgError, 0, null);
                        } finally {
                            waiting.dispose();
                        }

                    }
                }).start();
            }
        });        

        bt_exp.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                new Thread(new Runnable() {

                    public void run() {
                        waiting.showModeless();
                        try {
                            guardarPedido(leerRsPedido());
                            guardarDetalle(leerRsDetalle());
                        } catch (Exception e) {
                            e.printStackTrace();
                            Command okCommand = new Command("OK");
                            imgError = res.getImage("cancel.png");
                            Dialog.show("Falló!", "Error al exportar los datos:\n" + e.getMessage(),
                                    okCommand, new Command[]{okCommand}, Dialog.TYPE_ERROR, imgError, 0, null);
                        } finally {
                            waiting.dispose();
                        }

                    }
                }).start();
            }
        });

        bt_borrar = new Button("BORRAR DATOS");
        bt_borrar.getStyle().setMargin(3, 3, 5, 5);
        bt_borrar.setAlignment(CENTER);
        bt_borrar.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                if (Dialog.show("¿?", "ESTA SEGURO DE ELIMINAR LOS DATOS GUARDADOS EN LA APLICACIÓN?", "SI", "NO")) {
                    borrarRecords();
                }
            }
        });



        addComponent(bt_exp);
        //addComponent(bt_enviar_url);
        addComponent(new Label(""));
        /*Button dibujo = new Button(res.getImage("adBrowser.png"));
        dibujo.getStyle().setMargin(10, 10, 10, 10);
        dibujo.getStyle().setBorder(null, true);
        dibujo.setAlignment(CENTER);
        addComponent(dibujo);*/
        addComponent(bt_enviar_pedidos_web);
        addComponent(new Label(""));        
        addComponent(bt_borrar);


    }

    /**
     * Lee los datos del RecordStored PEDIDOS
     */
    private StringBuffer leerRsPedido() throws Exception {
        Persistencia p = null;
        StringBuffer datPed = new StringBuffer("");
        try {
            p = new Persistencia(PERS_PEDIDO);
            RecordEnumeration re = p.getRecordStore().enumerateRecords(null, null, false);
            while (re.hasNextElement()) {
                PersisPedido pd = new PersisPedido();
                pd.resurrect(re.nextRecord());
                datPed.append(pd.toString() + ENTER);
            }
        } finally {
            p.close();
        }
        return datPed;

    }
    
    /**
     * Lee los datos del RecordStored PEDIDOS para envio WEB
     */
    private StringBuffer leerRsPedidoWeb() throws Exception {
        Persistencia p = null;
        StringBuffer datPed = new StringBuffer("");
        try {
            p = new Persistencia(PERS_PEDIDO);
            RecordEnumeration re = p.getRecordStore().enumerateRecords(null, null, false);
            while (re.hasNextElement()) {
                PersisPedido pd = new PersisPedido();
                pd.resurrect(re.nextRecord());
                datPed.append(pd.toStringWeb());
            }
        } finally {
            p.close();
        }
        return datPed;

    }    

    /**
     * Lee los datos del RecordStored DETALLE
     */
    private StringBuffer leerRsDetalle() throws Exception {
        Persistencia p = null;
        StringBuffer datPed = new StringBuffer("");
        try {
            p = new Persistencia(PERS_DETALLE);
            RecordEnumeration re = p.getRecordStore().enumerateRecords(null, null, false);
            while (re.hasNextElement()) {
                PersisProducto pd = new PersisProducto();
                pd.resurrect(re.nextRecord());
                datPed.append(pd.toString() + ENTER);
            }
        } finally {
            p.close();
        }
        return datPed;
    }
    
        /**
     * Lee los datos del RecordStored DETALLE Web
     */
    private StringBuffer leerRsDetalleWeb() throws Exception {
        Persistencia p = null;
        StringBuffer datPed = new StringBuffer("");
        try {
            p = new Persistencia(PERS_DETALLE);
            RecordEnumeration re = p.getRecordStore().enumerateRecords(null, null, false);
            while (re.hasNextElement()) {
                PersisProducto pd = new PersisProducto();
                pd.resurrect(re.nextRecord());
                datPed.append(pd.toStringWeb());
            }
        } finally {
            p.close();
        }
        return datPed;
    }

    private void guardarPedido(final StringBuffer datos) throws IOException {
        escribirArchivo((ISENCAB ? CAB_PEDIDO : "")+ datos.toString(), getRuta() + NOM_ARC_PEDIDO);
    }

    private void escribirArchivo(String datos, String ruta) throws IOException {
        FileConnection fc = null;
        java.io.OutputStream os = null;
        try {
            fc = (FileConnection) Connector.open(ruta);
            if (!fc.exists()) {
                fc.create();
            } else {
                fc.truncate(0);
            }
            os = fc.openOutputStream();
            os.write(datos.getBytes());
        } finally {
            if (fc != null) {
                fc.close();
            }
            if (os != null) {
                os.flush();
                os.close();
            }
        }
    }

    private void guardarDetalle(final StringBuffer datos) throws IOException {
        escribirArchivo((ISENCAB ? CAB_DETALLE : "") + datos.toString(), getRuta() + NOM_ARC_DETALLE);
    }

    private void borrarRecords() {
        try {
            //borrar record Stored de pedidos
            RecordStore.deleteRecordStore(PERS_PEDIDO);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        try {
            //borrar record Stored de pedidos
            RecordStore.deleteRecordStore(PERS_DETALLE);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        try {
            //borrar record Stored del consecutivo de pedido
            RecordStore.deleteRecordStore(PERS_MAXPEDIDO);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    protected String getRuta() {
        Persistencia p = null;
        String ruta = "";
        try {
            p = new Persistencia(PERS_RUTA);
            RecordEnumeration re = p.getRecordStore().enumerateRecords(null, null, false);
            while (re.hasNextElement()) {
                ByteArrayInputStream bin = new ByteArrayInputStream(re.nextRecord());
                DataInputStream din = new DataInputStream(bin);
                ruta = din.readUTF();
                bin.close();
                din.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (p != null) {
                try {
                    p.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return ruta;
    }

  /*  private byte[] enviarFile() throws Exception {
        FileConnection fc = null;
        StringBuffer datos = new StringBuffer();
        InputStream din = null;

        String ruta = getRuta() + NOM_ARC_DETALLE;
        try {
            fc = (FileConnection) Connector.open(ruta);
            if (fc.exists()) {
                din = fc.openInputStream();
                int ch;
                while ((ch = din.read()) != -1) {
                    datos.append((char) ch);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fc != null) {
                fc.close();
            }
            if (din != null) {
                din.close();
            }
        }
        byte[] fileBytes = datos.toString().getBytes();


        Hashtable params = new Hashtable();
        params.put("Juser", EMPLEADO);
        params.put("Jpass", Rot13.encrip("javier"));

        Hashtable files = new Hashtable();
        files.put("file1",new FileInfo(NOM_ARC_DETALLE,"detalle","text/plain",fileBytes));
        files.put("file2",new FileInfo(NOM_ARC_PEDIDO,"pedido","text/plain",fileBytes));
        
        
        HttpMultipartRequest req = new HttpMultipartRequest(
                URL_SERVER,
                params,
                files);

        byte[] response = req.send();
        
        System.out.println("Res... " + new String(response));
        return response;

    } */

}
